package com.wanyangproject.fuwuactivity;

import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.wanyangproject.R;
import com.wanyangproject.entity.DengJiShiBaiEntity;
import com.wanyangproject.entity.TianJiaFangKeEntity;
import com.wanyangproject.popuwindow.SharePopupWindow;
import com.wanyangproject.popuwindow.ShareTuOianPopupWindow;
import com.wanyangproject.shouye.ShangJiaHuoDongXiangQingActivity;
import com.wanyangproject.utils.ContractUtils;
import com.wanyangproject.utils.JieShuYeMian;
import com.wanyangproject.utils.ShareUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.tencent.qq.QQ;
import okhttp3.Call;

//  添加访客
public class TianJiaFangKeActivity extends AppCompatActivity implements JieShuYeMian{

    @BindView(R.id.image_back)
    ImageView imageBack;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.et_people)
    EditText etPeople;
    @BindView(R.id.et_car)
    EditText etCar;
    @BindView(R.id.tv_lijitianjia)
    TextView tvLijitianjia;
    private TextView tv_quxiao, tv_queding;
    private NumberPicker numberPicker_year, numberPicker_month, numberPicker_day, numberPicker_hour, numberPicker_minute, province_picker, city_picker, qu_picker;
    private int year, month, day, hour, minute;
    private String string = "";//时间戳
    private Dialog dialogtishi;
    private TianJiaFangKeEntity tianjiaFangkeEntity;
    private ImageView imageTanchuang;
    private SharePopupWindow sharePopupWindow;
    private ShareTuOianPopupWindow shareTuOianPopupWindow;
    private int num = 11;

    private Context context;
    private TextView tv_weixin_haoyou,tv_qq_haoyou,tv_weixin_pengyouquan,tv_xinlang_weibo;
    //分享标题
    private String share_title="分享测试";
    //分享链接
//    private String share_url = "http://img.zcool.cn/community/0117e2571b8b246ac72538120dd8a4.jpg@1280w_1l_2o_100sh.jpg";
    //分享封面图片
    private String share_img = "http://img1.imgtn.bdimg.com/it/u=3044191397,2911599132&fm=26&gp=0.jpg";
    //分享描述
    private String share_desc="测试测试测试";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tian_jia_fang_ke);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 21) {
            View dview = getWindow().getDecorView();
            dview.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        DataShow();



//        if(etPhone!= null){
//            etPhone.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//                @Override
//                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                    if (actionId == EditorInfo.IME_ACTION_DONE) {//点击软键盘完成控件时触发的行为
//                        etPhone.setInputType(InputType.TYPE_NULL); // 关闭软键盘 return false; } });
//
////                        //关闭光标并且关闭软键盘
////                        etPhone.setCursorVisible(true);
////                        InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
////                        im.hideSoftInputFromWindow(getCurrentFocus().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//                    }
//                    return false;//消费掉该行为
//                }
//            });
//        }


        initView();


    }



    private void initView() {
        etPhone.addTextChangedListener(new TextWatcher() {
            //                        输入文字之前的状态
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                Log.i(TAG, "beforeTextChanged: ");
            }

            //            输入文字中的状态
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                Log.i(TAG, "onTextChanged: ");
            }

            //            输入文字之后的状态
            @Override
            public void afterTextChanged(Editable s) {


                int length = s.length();
                if(length >= num){
                    //将键盘下行
                    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                }


////                Log.i(TAG, "afterTextChanged: ");
//                int i = s.length();
//                if (s.length() > TV_NUMBER) {
//                    s.delete(TV_NUMBER, s.length());
//                    Toast.makeText(WorkActivity.this, "最多可以输入300个字", Toast.LENGTH_SHORT).show();
//                } else {
//                    int result = (number + i);
//                    tvNumberOne.setText(String.valueOf(result));
//                }
            }
        });
    }




//    public class MyEditTextChangeListener implements TextWatcher {
//        /**
//         * 编辑框的内容发生改变之前的回调方法
//         */
//        @Override
//        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
////            LogUtils.showLog("MyEditTextChangeListener", "beforeTextChanged---" + charSequence.toString());
//        }
//
//        /**
//         * 编辑框的内容正在发生改变时的回调方法 >>用户正在输入
//         * 我们可以在这里实时地 通过搜索匹配用户的输入
//         */
//        @Override
//        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
////            LogUtils.showLog("MyEditTextChangeListener", "onTextChanged---" + charSequence.toString());
//        }
//
//
//        /**
//         * 编辑框的内容改变以后,用户没有继续输入时 的回调方法
//         */
//        @Override
//        public void afterTextChanged(Editable editable) {
//            //将键盘下行
//            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
//            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
////            LogUtils.showLog("MyEditTextChangeListener", "afterTextChanged---");
//        }
//    }









    //    访客登记立即添加的网络请求
    private void initFangKeDengJiLiJiTianJiaHttp() {
        if(ContractUtils.isChinaPhoneLegal(etPhone.getText().toString().trim()) == false){
            Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        ContractUtils.isChinaPhoneLegal(etPhone.getText().toString().trim());

        System.out.println(tvTime.getText().toString().trim()+"             添加访客时间");
        final ProgressDialog progressDialog = new ProgressDialog(TianJiaFangKeActivity.this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("请等待...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "dengji/dengji")
                .addHeader("token", ContractUtils.getTOKEN(TianJiaFangKeActivity.this))
                .addParams("parkId", ContractUtils.getParkId(TianJiaFangKeActivity.this))
                .addParams("name", etName.getText().toString().trim())
                .addParams("phone", etPhone.getText().toString().trim())
                .addParams("nums", etPeople.getText().toString().trim())
                .addParams("chepai", etCar.getText().toString().trim())
                .addParams("daodaoTime", tvTime.getText().toString().trim())//时间戳
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressDialog.dismiss();

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response + "       访客登记立即添加的网络请求的网络请求");
                        ContractUtils.Code500(TianJiaFangKeActivity.this,response);
                        progressDialog.dismiss();

                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            tianjiaFangkeEntity = gson.fromJson(response, TianJiaFangKeEntity.class);
                            Toast.makeText(TianJiaFangKeActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                            TanChuang();
                        }else if(response.indexOf("400") != -1){
                            Gson gson = new Gson();
                            DengJiShiBaiEntity dengJiShiBaiEntity = gson.fromJson(response, DengJiShiBaiEntity.class);
                            Toast.makeText(TianJiaFangKeActivity.this, dengJiShiBaiEntity.getMsg(), Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }
                });
    }




    //    二维码提示框
    private void TanChuang() {
//        弹出二维码
        dialogtishi = new Dialog(this, R.style.Theme_Light_Dialog);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.tianjiefangke_erweima, null);
        Window window = dialogtishi.getWindow();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.CENTER);
        //设置dialog弹出时的动画效果，从屏幕底部向上弹出
        window.setWindowAnimations(R.style.dialogStyle);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        dialogtishi.setContentView(dialogView);
        dialogtishi.show();

        imageTanchuang = dialogtishi.getWindow().findViewById(R.id.image_tanchuang);
        if (ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + tianjiaFangkeEntity.getResponse().getPhoto() == null) {

        } else {
            Glide.with(TianJiaFangKeActivity.this).load(ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + tianjiaFangkeEntity.getResponse().getPhoto()).into(imageTanchuang);
        }


//        Drawable drawable = getResources().getDrawable(R.drawable.loginbaibian);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.loginbaibian);

        Object itemsOnClick = null;
        shareTuOianPopupWindow = new ShareTuOianPopupWindow(TianJiaFangKeActivity.this,(View.OnClickListener) itemsOnClick);
        shareTuOianPopupWindow.setIsOK(ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + tianjiaFangkeEntity.getResponse().getPhoto());

        shareTuOianPopupWindow.setTupian(ContractUtils.YUANQUZHAOSHANG_PHOTO_URL+"/"+tianjiaFangkeEntity.getResponse().getLogo());
        shareTuOianPopupWindow.setBitmap(bitmap);
        System.out.println(ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + tianjiaFangkeEntity.getResponse().getPhoto()+"    图片链接");
        shareTuOianPopupWindow.setJieShuYeMian(this);


        dialogtishi.getWindow().findViewById(R.id.tv_fenxiang).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogtishi.dismiss();
                shareTuOianPopupWindow.showAtLocation(findViewById(R.id.relative_Layout), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }
        });



        dialogtishi.getWindow().findViewById(R.id.tv_duanxin).setOnClickListener(
                new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogtishi.dismiss();
                //                判断当前SDK版本号
                if (Build.VERSION.SDK_INT >= 23) {
//                    当前拨打电话权限是没有给的
                    if (ContextCompat.checkSelfPermission(TianJiaFangKeActivity.this, Manifest.permission.RECEIVE_MMS) != PackageManager.PERMISSION_GRANTED) {
//                        我要请求权限
                        ActivityCompat.requestPermissions(TianJiaFangKeActivity.this, new String[]{Manifest.permission.RECEIVE_MMS}, 1);
                    } else {
//                        ShareUtils.shareshortmessage(share_title,ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + tianjiaFangkeEntity.getResponse().getPhoto(),share_desc,share_img,platformActionListener);
                        Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"));
                        intent.putExtra("sms_body", ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + tianjiaFangkeEntity.getResponse().getPhoto());
                        startActivity(intent);
                    }
                } else {
//                    ShareUtils.shareshortmessage(share_title,ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + tianjiaFangkeEntity.getResponse().getPhoto(),share_desc,share_img,platformActionListener);
                    Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"));
                    intent.putExtra("sms_body", ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + tianjiaFangkeEntity.getResponse().getPhoto());
                    startActivity(intent);
                }
            }
        });
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (permissions.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    ShareUtils.shareshortmessage(share_title,ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + tianjiaFangkeEntity.getResponse().getPhoto(),share_desc,share_img,platformActionListener);
                    Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"));
                    intent.putExtra("sms_body", ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + tianjiaFangkeEntity.getResponse().getPhoto());
                    startActivity(intent);

                } else {
                    Toast.makeText(TianJiaFangKeActivity.this, "", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
//
//
//    /**
//     * 分享回调
//     */
//    PlatformActionListener platformActionListener=new PlatformActionListener() {
//        @Override
//        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//            Toast.makeText(context, "分享成功", Toast.LENGTH_SHORT).show();
//        }
//
//        @Override
//        public void onError(Platform platform, int i, Throwable throwable) {
//            Toast.makeText(context, "分享失败", Toast.LENGTH_SHORT).show();
//        }
//
//        @Override
//        public void onCancel(Platform platform, int i) {
//            Toast.makeText(context, "分享取消", Toast.LENGTH_SHORT).show();
//        }
//    };
//





    private void DataShow() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
//获取当前时间
        Date date = new Date(System.currentTimeMillis());
        System.out.println("Date获取当前日期时间" + simpleDateFormat.format(date));
//                                    2018年03月14日 11:39:29
        String str = simpleDateFormat.format(date);

        year = Integer.parseInt(str.substring(0, 4));
        month = Integer.parseInt(str.substring(5, 7));
        day = Integer.parseInt(str.substring(8, 10));
        hour = Integer.parseInt(str.substring(12, 14));
        minute = Integer.parseInt(str.substring(15, 17));
    }


    @OnClick({R.id.image_back, R.id.et_name, R.id.et_phone, R.id.tv_time, R.id.et_people, R.id.et_car, R.id.tv_lijitianjia})
    public void onViewClicked(View view) {
        switch (view.getId()) {
//            返回按钮
            case R.id.image_back:
                finish();
                break;
//            访客姓名
            case R.id.et_name:
                break;
//           访客电话
            case R.id.et_phone:
                break;
//            预计到访时间
            case R.id.tv_time:
                Calendar calendar = Calendar.getInstance();

                TimePickerView timePickerView = new TimePickerView.Builder(TianJiaFangKeActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        tvTime.setText(simpleDateFormat1.format(date));
//                        try {
//                            Date date1 = simpleDateFormat1.parse(tvTime.getText().toString());
//                            long time = date1.getTime();
//                            string = String.valueOf(time);
//                            System.out.println(string + "     时间戳");
//                        } catch (ParseException e) {
//                            e.printStackTrace();
//                        }
                    }
                })
                        .setType(new boolean[]{true, true, true, true, true, false})//默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setTextXOffset(0, 0, 0, 0, 0, 0)
                        .setLunarCalendar(false)
                        .setContentSize(14)//滚轮文字大小
                        .gravity(Gravity.CENTER)
                        .setLineSpacingMultiplier(2.8f)//设置两横线之间的间隔倍数
                        .setTitleSize(16)//标题文字大小
                        .setTitleText("到访时间")//标题文字
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(false)//是否循环滚动
                        .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                        .setTextColorOut(Color.parseColor("#AEAAAA"))
                        .setTitleColor(Color.BLACK)//标题文字颜色
                        .setSubmitColor(Color.RED)//确定按钮文字颜色
                        .setCancelColor(Color.parseColor("#AEAAAA"))//取消按钮文字颜色
                        .setTitleBgColor(Color.parseColor("#f5f5f5"))//标题背景颜色 Night mode
                        .setBgColor(Color.parseColor("#ffffff"))//滚轮背景颜色 Night mode
                        .setRange(calendar.get(Calendar.YEAR), 2100)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                        .setRangDate(startDate,endDate)//起始终止年月日设定
                        .setLabel("年", "月", "日", ":", "", "")
                        .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                        .isDialog(false)//是否显示为对话框样式
                        .build();
                timePickerView.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                timePickerView.show();



                break;
//            到访人数
            case R.id.et_people:
                break;
//            车牌号
            case R.id.et_car:
                break;
//            立即添加
            case R.id.tv_lijitianjia:

                Calendar instance = Calendar.getInstance();

                int year = instance.get(Calendar.YEAR);
                int month = instance.get(Calendar.MONTH)+1;// 获取当前月份
                int day = instance.get(Calendar.DAY_OF_MONTH);// 获取当日期
                int hour = instance.get(Calendar.HOUR_OF_DAY);//日
                int minute = instance.get(Calendar.MINUTE);//时
                int miao = instance.get(Calendar.SECOND);//分
                System.out.println(month+"      month");
                System.out.println(day+"      day");
                System.out.println(hour+"       hour");
                System.out.println(minute+"         minute");
                System.out.println(miao+"         miao");
                System.out.println(tvTime.getText().toString().trim()+"         tvTime");


                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    Date date = sdf.parse(tvTime.getText().toString().trim());
                    System.out.println(date+"    date");
                    System.out.println(date.getTime()+"            date.getTime()");
//                    Date date1 = sdf.parse(year+"-"+month+"-"+day+" "+hour+":"+minute+":"+miao);
                    Date date1 = sdf.parse(year+"-"+month+"-"+day+" "+hour+":"+minute);
                    System.out.println(year+"-"+month+"-"+day+" "+hour+":"+minute+"         时间时间");

//                    输入框时间            系统时间
                    if(date.getTime() <= date1.getTime()){
                        Toast.makeText(this, "请输入正确的时间！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

//









                if (etName.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "请输入访客姓名", Toast.LENGTH_SHORT).show();
                } else if (etPhone.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "请输入访客电话", Toast.LENGTH_SHORT).show();
                } else if (tvTime.getText().toString().equals("")) {
                    Toast.makeText(this, "请选择预计到访时间", Toast.LENGTH_SHORT).show();
                } else if (etPeople.getText().toString().trim().equals("") || etPeople.getText().toString().trim().equals("0")) {
                    Toast.makeText(this, "请输入预计到访人数", Toast.LENGTH_SHORT).show();
                } else {
                    //        访客登记立即添加的网络请求
                    initFangKeDengJiLiJiTianJiaHttp();
                }

                break;
        }
    }

    @Override
    public void jieshu() {
        finish();
    }



}
